package dbConnect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class dbConnecter {
    public final static String username = "text";
    public final static String psw = "1234";
    public final static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=stu;";
    public Connection conn = null;
    public Statement statement=null;

    public static String toSql(String str){
        return "'" + str + "'";
    }
    public static String toSqlint(int i){
        return  "'" + i +"'";
    }
    public static boolean toResult(int rs){
        if(rs == 1)
            return true;
        else
            return false;
    }

    public void getConnection(){
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn = DriverManager.getConnection(url,username,psw);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public int resultSql(String sql) throws  Exception
    {
        int result;
        statement = conn.createStatement();
        result = statement.executeUpdate(sql);
        return result;
    }
    public ResultSet querySql(String sql)throws Exception
    {
        ResultSet rs = null;//声明返回结果
        statement = conn.createStatement();
        rs = statement.executeQuery(sql);
        return rs;
    }
    public String close(){
        String rs = "";
        try {
            if (conn!=null)
            {
                conn.close();
            }
            rs = "success";
        }catch (Exception e){
            e.printStackTrace();
            rs = "failure";
        }
        return rs;
    }

    public  static void main(String[] args)throws Exception{
        dbConnecter conn = new dbConnecter();
        conn.getConnection();
        String sql = "select * from sudent";
        ResultSet rs = null;
        rs = conn.querySql(sql);
        while(rs.next()){
            int id = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println("Sno:"+id+"" +"\tSame:"+name);
        }
        conn.close();
    }
}
